package com.tanhua.dubbo.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.api.db.UserApi;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mapper.UserInfoMapper;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务提供者
 */
@DubboService
public class UserInfoApiImpl implements UserInfoApi {

    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 保存用户信息
     * @param userInfo
     */
    @Override
    public void add(UserInfo userInfo) {
        userInfoMapper.insert(userInfo);
    }

    /**
     * 更新头像
     * @param userInfo
     */
    @Override
    public void upload(UserInfo userInfo) {
        userInfoMapper.updateById(userInfo);
    }

    /**
     * 查询用户信息
     * @param userId
     * @return
     */
    @Override
    public UserInfo findById(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        return userInfo;
    }

    /**
     * 用户资料 - 保存
     * @param userInfo
     */
    @Override
    public void updateUserInfo(UserInfo userInfo) {
        userInfoMapper.updateById(userInfo);
    }

    /**
     * 根据黑名单用户ids调用服务查询黑名单用户集合数据
     * @param blackListIds
     * @return
     */
    @Override
    public List<UserInfo> findByBatchIds(List<Long> blackListIds) {
        List<UserInfo> userInfos = userInfoMapper.selectBatchIds(blackListIds);
        return userInfos;
    }

    @Override
    public Map<Long, UserInfo> findByIds(List<Long> listUserIds, UserInfo userInfoCondition) {

        //1.定义Map<Long, UserInfo> 结果返回
        Map<Long, UserInfo> userInfoMap  = new HashMap<>();

        //2.根据listUserids userInfoCondtion 进行条件查询
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        if(!CollectionUtils.isEmpty(listUserIds)) {
            queryWrapper.in("id", listUserIds);
        }
        if(userInfoCondition != null) {
            if(userInfoCondition.getAge() != null) {
                queryWrapper.lt("age", userInfoCondition.getAge());
            }
            if(userInfoCondition.getGender() != null) {
                queryWrapper.eq("gender", userInfoCondition.getGender());
            }
            if(userInfoCondition.getNickname() != null){
                queryWrapper.like("nickname", userInfoCondition.getNickname());
            }
        }
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);

        //3.封装结果返回
        for (UserInfo userInfo : userInfoList) {
            Long id = userInfo.getId();
            userInfoMap.put(id,userInfo);
        }
        return userInfoMap;
    }

}
